﻿import El from '/vue/el/index.esm.browser.js'
import store from '/vue/store/index.js'
import { getToken } from '/vue/utils/auth.js'
import router from '/vue/router/index.js'
import Clipboard from '/vue/libs/clipboard.min.js'

//剪贴板助手
$("<textarea id='ClipboardHelper' style='display:none;' />").appendTo("body");
var clipBoard = new Clipboard('#ClipboardHelper', {
	text: function () {
		return $("#ClipboardHelper").val();
	}
});
clipBoard.on('success', function (event) {

});
clipBoard.on('error', function (error) {

});

// create an axios instance
const service = axios.create({
	//baseURL: "", // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent

		if (store.getters.token) {
			// let each request carry token
			// ['X-Token'] is a custom headers key
			// please modify it according to the actual situation
			config.headers['X-Token'] = getToken()
		}
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	*/

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	response => {
		const data = response.data
		if (typeof data === "string") {
			return data;
		}
		if (!data.code) {
			return Promise.reject(new Error('返回的json对象必须设置code属性'))
		}
		
		if (data.code === 50014) {
			setTimeout(function () {//等待一会，看是否下一个页面本身就是login
				if (router.history.current.path.toLowerCase() !== "/login") {//不是login
					El.MessageBox.confirm("会话过期！", '确认退出', {
						confirmButtonText: '重新登录',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						store.dispatch('user/resetToken').then(() => {
							location.reload();							
						})
					}, () => { });
				}
				else {//是login，不用弹框了
					store.dispatch('user/resetToken');
				}
			}, 500);
			return Promise.reject(new Error("会话过期"));
		}
		if (data.code === 50000) {
			let err = data.path + "\r\n" + data.msg + "\r\n" + data.trace;
			El.MessageBox.confirm(data.msg, '后台出错', {
				confirmButtonText: '复制',
				cancelButtonText: '取消',
				type: 'error'
			}).then(() => {
				$("#ClipboardHelper").val(err).click();
			}, () => { });
			return Promise.reject(new Error(err));
		}
		if (data.code === 40000) {
			let err = "请求路径不存在：" + data.path;
			El.MessageBox.confirm(data.path, '404错误', {
				confirmButtonText: '复制',
				cancelButtonText: '取消',
				type: 'error'
			}).then(() => {
				$("#ClipboardHelper").val(err).click();
			}, () => { });
			return Promise.reject(new Error(err));
		}

		if (data.code !== 20000) {
			El.Message({
				message: data.message || 'Error',
				type: 'error',
				duration: 5 * 1000
			});

			return Promise.reject(new Error(data.message || 'Error'));
		}
		return data
	},
	error => {
		console.log('err' + error) // for debug
		El.Message({
			message: error.message,
			type: 'error',
			duration: 5 * 1000
		})
		return Promise.reject(error)
	}
)

export default service
